import React, { useRef, useState } from 'react'
import { DatePicker, Select, Input, Button } from 'antd';
import styles from '../../styles/classroom/borrowInfo.scss'
import { withRouter } from 'next/router'
import moment from 'moment';
import { PlusOutlined } from '@ant-design/icons';
import { getToken } from '../common/util';
import { error, axiosConfig, backIP, success } from '../common/config';
import axios from 'axios'

const { Option } = Select;
const dateFormat = 'YYYY/MM/DD';
const { TextArea } = Input;

// 获取现在的时间
const nowDate = new Date()
const nowYear = nowDate.getFullYear();
const nowMonth = nowDate.getMonth() + 1;
const nowDay = nowDate.getDate();

function BorrowInfo({ router, currentCourse, setCurrentCourse }) {
    const [imgUrl, setImgUrl] = useState('')
    const [selectDate, setSelectDate] = useState(new Date())
    const imageRef = useRef();
    const informationRef = useRef();

    const handleDataChange = (date, dateString) => {
        date ? setSelectDate(date._d as Date) : setSelectDate(null)
    }
    const handleCourseChange = (value) => {
        setCurrentCourse(value)
    }
    const uploadImage = async () => {
        const token: string = getToken();
        if (!token) {
            error('token已失效，请重新登录')
        }
        const formData = new FormData()
        formData.append('uploadfile', (imageRef.current as any).files[0])
        const { data: res }: { data: axiosConfig } = await axios({
            url: `${backIP}/avatar`,
            method: 'put',
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data', Authorization: token }
        })
        if (res.code === 0) {
            console.log(res.data)
            setImgUrl(res.data)
        } else {
            error(res.message);
        }
    }
    const handleSubmit = async () => {
        const classID: number = router.query.class;
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.post(`${backIP}/borrowClass`, {
            borrow_year: selectDate.getFullYear(),
            borrow_month: selectDate.getMonth() + 1,
            borrow_day: selectDate.getDate(),
            class_id: classID,
            course: currentCourse,
            certificate: imgUrl,
            information: (informationRef.current as any).state.value
        }, {
            headers: {
                Authorization: token,
            }
        });
        if (res.code === 0) {
            success(res.message)
        } else {
            error(res.message)
        }
    }

    return (
        <div className={styles.layout}>
            <div className={styles.header}>
                <DatePicker
                    defaultValue={moment(`${nowYear}/${nowMonth}/${nowDay}`, dateFormat)}
                    format={dateFormat}
                    onChange={handleDataChange}
                />
                <Select defaultValue={currentCourse || 1} style={{ width: 120 }} onChange={handleCourseChange}>
                    <Option value={1}>第一二节课</Option>
                    <Option value={2}>第三四节课</Option>
                    <Option value={3}>第五六节课</Option>
                    <Option value={4}>第七八节课</Option>
                </Select>
            </div>
            <div className={styles.inputInfos}>
                <div>
                    <span className={styles.title}>原因</span>
                    <TextArea
                        rows={8}
                        className={styles.input}
                        ref={informationRef}
                        placeholder='请输入申请教室的理由'
                    />
                </div>
                <div>
                    <span className={styles.title}>一卡通照片</span>
                    <input
                        type="file"
                        ref={imageRef}
                        className={styles.fileInput}
                        onChange={uploadImage}
                    />
                    <div className={styles.selectImg}>
                        {
                            imgUrl
                                ? <img src={imgUrl} alt="" className={styles.fillImg} />
                                : <PlusOutlined className={styles.selectIcon} />
                        }
                    </div>
                </div>
            </div>
            <Button
                type="primary"
                className={styles.submitBtn}
                onClick={handleSubmit}
            >
                提交
            </Button>
        </div>
    )
}

export default withRouter(BorrowInfo);